import { _decorator, AssetManager, Component, Node, Quat, v3, Vec3 } from 'cc';
import { TankAstar } from './TankAstar';
import { TankShooting } from './TankShooting';
import { TankManager } from '../Managers/TankManager';
import { AStarPathfinder } from '../Astar/AstarPathfinder';
import { Astarmanager } from '../Astar/Astarmanager';
const { ccclass, property } = _decorator;

@ccclass('TankAI')
export class TankAI extends Component {

    tankAstart: TankAstar = null;

    shooting: TankShooting = null;

    private _shootTimer: number = 0;

    distance: number = 0;

    tankPlayer: TankManager = null;

    start() {
        this.tankAstart = this.node.getComponent(TankAstar)
        this.shooting = this.node.getComponent(TankShooting)
        const impactPos = this.shooting.calculateGroundImpact();
        this.distance = Math.sqrt(
            Math.pow(impactPos.x - this.node.position.x, 2) +
            Math.pow(impactPos.y - this.node.position.y, 2) +
            Math.pow(impactPos.z - this.node.position.z, 2)
        );
        this.tankPlayer = Astarmanager.getInstance().tank;
    }

    judgefire() {
        const impactPos = this.shooting.calculateGroundImpact();

        if (this.isPointInCircleXZ(this.tankPlayer.instance.worldPosition, impactPos, 5)) {
            this.shooting.fire();
        }
    }

    judgefind() {
        if (this.isPointInCircleXZ(this.node.worldPosition, this.tankPlayer.instance.worldPosition, this.distance - 3)) {
            this.tankAstart.enabled = false;
            const pos = this.node.worldPosition;
            const dx = this.tankPlayer.instance.position.x - this.node.position.x;
            const dz = this.tankPlayer.instance.position.z - this.node.position.z;
            const distance = Math.sqrt(dx * dx + dz * dz);
            const direction = new Vec3(dx / distance, 0, dz / distance);
            const targetAngle = Math.atan2(direction.x, direction.z) * 180 / Math.PI;
            // const currentAngle = this.node.eulerAngles.y;
            // const lerpFactor = 0.1; // Adjust this value for faster/slower rotation (0-1)
            // const smoothedAngle = currentAngle + (targetAngle - currentAngle) * lerpFactor;
            this.node.setRotationFromEuler(0, targetAngle, 0);
            this.node.worldPosition = new Vec3(pos.x, 0.05, pos.z);
        }
        else {
            this.tankAstart.enabled = true;

        }
    }

    update(deltaTime: number) {
        this._shootTimer += deltaTime;
        if (this._shootTimer >= 1.0) {
            this.judgefire();
            this._shootTimer = 0;
        }
        this.judgefind();
    }



    isPointInCircleXZ(point: Vec3, center: Vec3, radius: number): boolean {
        // 计算两点在XZ平面上的距离平方
        const dx = point.x - center.x;
        const dz = point.z - center.z;
        const distanceSquared = dx * dx + dz * dz;

        // 比较距离平方与半径平方（避免开平方运算提高性能）
        return distanceSquared <= radius * radius;
    }
}

